"""
Web
"""

import streamlit as st
import json
from datetime import timedelta

class ResultDisplay:
    """"""
    
    def render(self, result_data, settings):
        """"""
        if not result_data:
            st.warning("")
            return
        
        st.header(" ")
        
        # 
        self._render_statistics(result_data)
        
        # 
        tab1, tab2, tab3, tab4 = st.tabs([" ", " ", " ", " "])
        
        with tab1:
            self._render_summary_tab(result_data)
        
        with tab2:
            self._render_keywords_tab(result_data)
        
        with tab3:
            self._render_chapters_tab(result_data)
        
        with tab4:
            self._render_transcript_tab(result_data)
        
        # 
        self._render_download_buttons(result_data, settings)
    
    def _render_statistics(self, result_data):
        """"""
        col1, col2, col3, col4 = st.columns(4)
        
        with col1:
            language = result_data.get('transcript', {}).get('language', '')
            st.metric(" ", language)
        
        with col2:
            text_length = len(result_data.get('transcript', {}).get('text', ''))
            st.metric(" ", f"{text_length} ")
        
        with col3:
            segments = result_data.get('transcript', {}).get('segments', [])
            st.metric(" ", len(segments))
        
        with col4:
            summary_length = len(result_data.get('summary', {}).get('summary', ''))
            st.metric(" ", f"{summary_length} ")
    
    def _render_summary_tab(self, result_data):
        """"""
        summary_data = result_data.get('summary', {})
        
        if 'summary' in summary_data:
            st.subheader(" ")
            st.write(summary_data['summary'])
            
            # 
            if 'quality_rating' in summary_data:
                st.subheader(" ")
                col1, col2 = st.columns(2)
                with col1:
                    st.metric("", summary_data['quality_rating'])
                with col2:
                    compression_ratio = summary_data.get('summary_ratio', 0)
                    st.metric("", f"{compression_ratio:.2%}")
        else:
            st.info("")
    
    def _render_keywords_tab(self, result_data):
        """"""
        summary_data = result_data.get('summary', {})
        keywords = summary_data.get('keywords', [])
        
        if keywords:
            st.subheader(" ")
            
            # 
            cols = st.columns(3)
            for i, keyword in enumerate(keywords):
                with cols[i % 3]:
                    st.button(keyword, key=f"keyword_{i}")
        else:
            st.info("")
    
    def _render_chapters_tab(self, result_data):
        """"""
        summary_data = result_data.get('summary', {})
        chapters = summary_data.get('chapters', [])
        
        if chapters:
            st.subheader(" ")
            
            for chapter in chapters:
                with st.expander(f"{chapter['chapter']}: {chapter['title']}"):
                    col1, col2 = st.columns([3, 1])
                    with col1:
                        st.write(chapter['content'][:200] + "..." if len(chapter['content']) > 200 else chapter['content'])
                    with col2:
                        st.metric("", chapter['word_count'])
                        start_time = str(timedelta(seconds=chapter.get('start_time', 0)))
                        st.metric("", start_time)
        else:
            st.info("")
    
    def _render_transcript_tab(self, result_data):
        """"""
        transcript_data = result_data.get('transcript', {})
        
        if 'text' in transcript_data:
            st.subheader(" ")
            st.text_area(
                "",
                value=transcript_data['text'],
                height=400,
                help=""
            )
        else:
            st.info("")
    
    def _render_download_buttons(self, result_data, settings):
        """"""
        st.subheader(" ")
        
        formats = settings.get('output_formats', ['txt'])
        cols = st.columns(len(formats))
        
        for i, fmt in enumerate(formats):
            with cols[i]:
                content = self._generate_content(result_data, fmt)
                if content:
                    filename = f"video_summary.{fmt}"
                    mime_type = self._get_mime_type(fmt)
                    
                    st.download_button(
                        label=f"  {fmt.upper()}",
                        data=content,
                        file_name=filename,
                        mime=mime_type,
                        key=f"download_{fmt}"
                    )
    
    def _generate_content(self, result_data, format_type):
        """"""
        try:
            if format_type == 'txt':
                return result_data.get('transcript', {}).get('text', '')
            elif format_type == 'json':
                return json.dumps(result_data, ensure_ascii=False, indent=2)
            elif format_type == 'md':
                return self._generate_markdown_content(result_data)
            elif format_type == 'srt':
                return self._generate_srt_content(result_data)
            elif format_type == 'vtt':
                return self._generate_vtt_content(result_data)
            elif format_type == 'html':
                return self._generate_html_content(result_data)
        except Exception as e:
            st.error(f" {format_type} : {e}")
            return None
    
    def _generate_markdown_content(self, result_data):
        """Markdown"""
        content = "# \n\n"
        
        # 
        summary_data = result_data.get('summary', {})
        if 'summary' in summary_data:
            content += "##  \n\n"
            content += summary_data['summary'] + "\n\n"
        
        # 
        keywords = summary_data.get('keywords', [])
        if keywords:
            content += "##  \n\n"
            content += ", ".join(keywords) + "\n\n"
        
        # 
        chapters = summary_data.get('chapters', [])
        if chapters:
            content += "##  \n\n"
            for chapter in chapters:
                content += f"### {chapter['chapter']}: {chapter['title']}\n\n"
                content += chapter['content'] + "\n\n"
        
        return content
    
    def _generate_srt_content(self, result_data):
        """SRT"""
        transcript_data = result_data.get('transcript', {})
        segments = transcript_data.get('segments', [])
        
        if not segments:
            return f"1\n00:00:00,000 --> 99:59:59,999\n{transcript_data.get('text', '')}\n"
        
        srt_content = ""
        for i, segment in enumerate(segments, 1):
            start_time = self._format_time_srt(segment['start'])
            end_time = self._format_time_srt(segment['end'])
            text = segment['text'].strip()
            
            srt_content += f"{i}\n{start_time} --> {end_time}\n{text}\n\n"
        
        return srt_content
    
    def _generate_vtt_content(self, result_data):
        """VTT"""
        vtt_content = "WEBVTT\n\n"
        
        transcript_data = result_data.get('transcript', {})
        segments = transcript_data.get('segments', [])
        
        if not segments:
            vtt_content += f"00:00:00.000 --> 99:59:59.999\n{transcript_data.get('text', '')}\n"
            return vtt_content
        
        for segment in segments:
            start_time = self._format_time_vtt(segment['start'])
            end_time = self._format_time_vtt(segment['end'])
            text = segment['text'].strip()
            
            vtt_content += f"{start_time} --> {end_time}\n{text}\n\n"
        
        return vtt_content
    
    def _generate_html_content(self, result_data):
        """HTML"""
        html_content = """
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        h1, h2 { color: #333; }
        .summary { background: #f5f5f5; padding: 20px; border-radius: 5px; }
        .keywords { margin: 20px 0; }
        .keyword { background: #e3f2fd; padding: 5px 10px; margin: 5px; border-radius: 15px; display: inline-block; }
        .chapter { margin: 20px 0; padding: 15px; border-left: 4px solid #2196f3; }
    </style>
</head>
<body>
    <h1> </h1>
"""
        
        # 
        summary_data = result_data.get('summary', {})
        if 'summary' in summary_data:
            html_content += f"""
    <h2> </h2>
    <div class="summary">{summary_data['summary']}</div>
"""
        
        # 
        keywords = summary_data.get('keywords', [])
        if keywords:
            html_content += """
    <h2> </h2>
    <div class="keywords">
"""
            for keyword in keywords:
                html_content += f'        <span class="keyword">{keyword}</span>\n'
            html_content += "    </div>\n"
        
        # 
        chapters = summary_data.get('chapters', [])
        if chapters:
            html_content += "    <h2> </h2>\n"
            for chapter in chapters:
                html_content += f"""
    <div class="chapter">
        <h3>{chapter['chapter']}: {chapter['title']}</h3>
        <p>{chapter['content']}</p>
    </div>
"""
        
        html_content += """
</body>
</html>
"""
        return html_content
    
    def _format_time_srt(self, seconds):
        """SRT"""
        td = timedelta(seconds=seconds)
        hours, remainder = divmod(td.total_seconds(), 3600)
        minutes, seconds = divmod(remainder, 60)
        milliseconds = int((seconds % 1) * 1000)
        return f"{int(hours):02d}:{int(minutes):02d}:{int(seconds):02d},{milliseconds:03d}"
    
    def _format_time_vtt(self, seconds):
        """VTT"""
        return self._format_time_srt(seconds).replace(',', '.')
    
    def _get_mime_type(self, format_type):
        """MIME"""
        mime_types = {
            'txt': 'text/plain',
            'json': 'application/json',
            'md': 'text/markdown',
            'srt': 'text/plain',
            'vtt': 'text/vtt',
            'html': 'text/html'
        }
        return mime_types.get(format_type, 'text/plain')